# -*- coding: utf-8 -*-
# @Time : 2022/4/7 16:02
# @FileName: LoadWidget.py

__author__ = 'Zhigen.li'

import os
import sys
import time
from threading import Thread
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtCore import Qt, QPoint, pyqtSignal
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from UI.AccurateWidget import AccurateWidget
from Tools.Util import *
from res.resource_rc import *
from apscheduler.schedulers.blocking import BlockingScheduler
from Config.Config import config, CatchExceptions


class LoadWidget(QWidget):
    enterLoadWidSignal = pyqtSignal()
    updateAccurateSignal = pyqtSignal(str, str, str)
    moveSignal = pyqtSignal(int)
    resizeSignal = pyqtSignal(int, int)
    logSignal = pyqtSignal(str)

    def __init__(self, parent):
        super(LoadWidget, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.BypassWindowManagerHint | Qt.Tool | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.resize(24, 91)
        self.setAttribute(Qt.WA_Mapped)
        self.moveSignal.connect(self.onMove)
        self.resizeSignal.connect(self.onResize)

    def onLogin(self):
        self.accurateWidget = AccurateWidget(self.parent())
        self.logSignal.connect(self.accurateWidget.onLog)
        self.logSignal.emit('登陆成功')
        funds = config.getFund()
        for f in funds:
            try:
                data = fundAccurate(f['fundcode'])
                self.accurateWidget.addAccurate(data['name'], data['gszzl'], data['gztime'])
            except Exception as e:
                QMessageBox.warning(None, '错误信息', str(e))
        self.enterLoadWidSignal.connect(self.accurateWidget.onEnterLoadWid)
        self.updateAccurateSignal.connect(self.accurateWidget.onUpdateAccurate)
        self.accurateWidget.leaveAccurateWidSignal.connect(self.onLeaveAccurateWid)
        self.accurateWidget.fundSateChangedSignal.connect(self.onFundSateChanged)
        self.accurateWidget.hideLoadWidSignal.connect(self.onHideLoadWid)

        if config.getFixed():
            self.enterLoadWidSignal.emit()
            self.setHidden(True)

        # 定时获取净值估算
        self.th = Thread(target=self.startSched)
        self.th.setDaemon(True)
        self.th.start()
        self.show()

        #  移动效果
        moveThread = Thread(target=self.moveFunc)
        moveThread.start()

    def getSettingDialog(self):
        return self.accurateWidget.getSettingDialog()

    def moveFunc(self):
        screen = QGuiApplication.primaryScreen()
        mm = screen.availableGeometry()
        screen_width = mm.width()
        needMoveX = (screen_width - self.width()) - (screen_width - self.width()) // 2
        temp = needMoveX
        while needMoveX > 0:
            needMoveX -= 10
            self.moveSignal.emit((screen_width - self.width()) // 2 + (temp - needMoveX))
            time.sleep(0.002)
        # self.resizeSignal.emit(24 * 2, 91 * 2)
        # self.moveSignal.emit(screen_width - self.width())
        # time.sleep(0.5)
        # self.resizeSignal.emit(24, 91)
        # self.moveSignal.emit(screen_width - self.width())
        # time.sleep(0.5)
        # self.resizeSignal.emit(24 * 2, 91 * 2)
        # self.moveSignal.emit(screen_width - self.width())
        # time.sleep(0.5)
        # self.resizeSignal.emit(24, 91)
        # self.moveSignal.emit((screen_width - self.width()) // 2 + temp)

    def onMove(self, x):
        screen = QGuiApplication.primaryScreen()
        mm = screen.availableGeometry()
        screen_height = mm.height()
        self.move(QPoint(x, (screen_height - self.height()) // 2))

    def onResize(self, w, h):
        self.resize(w, h)

    def startSched(self):
        self.sched = BlockingScheduler()
        self.sched.add_job(self.timedTask, trigger='cron', name='job1', hour='9', minute='25,30,35,40,45,50,55')
        self.sched.add_job(self.timedTask, trigger='cron', name='job2', hour='10,11,13,14', minute='0,5,10,15,20,25,30,35,40,45,50,55')
        self.sched.add_job(self.timedTask, trigger='cron', name='job3', hour='15', minute='0,5')
        self.logSignal.emit('添加定时刷新基金净值估算任务')
        self.sched.start()

    def timedTask(self):
        funds = config.getFund()
        for f in funds:
            try:
                data = fundAccurate(f['fundcode'])
                self.updateAccurateSignal.emit(data['name'], data['gszzl'], data['gztime'])
                print(data)
            except Exception as e:
                print(e)

    def onLeaveAccurateWid(self):
        self.setHidden(False)
        self.show()

    def onHideLoadWid(self):
        self.setHidden(True)

    def onFundSateChanged(self):
        self.accurateWidget.clear()
        funds = config.getFund()
        for f in funds:
            try:
                data = fundAccurate(f['fundcode'])
                self.accurateWidget.addAccurate(data['name'], data['gszzl'], data['gztime'])
            except Exception as e:
                QMessageBox.warning(None, '错误信息', str(e))

    def enterEvent(self, a0):
        self.enterLoadWidSignal.emit()
        self.setHidden(True)
        return super(LoadWidget, self).enterEvent(a0)

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHints(QPainter.RenderHint.SmoothPixmapTransform, True)
        pixmap = QPixmap(':/Img/44.png')
        qp.drawPixmap(self.rect(), pixmap)

    def closeEvent(self, a0):
        self.sched.remove_all_jobs()
        self.sched.shutdown()
        if self.th.is_alive():
            self.th.join()
        super(LoadWidget, self).closeEvent(a0)


# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     w = LoadWidget()
#     w.show()
#     sys.exit(app.exec())